import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { Message, Loading } from 'element-ui'
// 响应时间
axios.defaults.timeout = 10 * 1000
// 配置cookie
axios.defaults.withCredentials = false
// 配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// 静态资源
Vue.prototype.$static = ''

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10 * 1000 // request timeout
})

let loadingInstance
// 请求拦截器
service.interceptors.request.use(
  config => {
    const {
      showing = true
    } = qs.parse(config.data)
    if (showing) {
      loadingInstance = Loading.service({
        lock: true,
        text: '数据加载中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    if (config.method === 'post') {
      config.data = `${qs.stringify(config.data)}`
    }
    if (config.method === 'upload') {
      config.method = 'post'
      config.headers = { 'Content-Type': 'multipart/form-data;charset=utf-8' }
    }
    return config
  },
  err => {
    loadingInstance.close()
    Message.error('请求错误')
    return Promise.reject(err)
  }
)

// 返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  res => {
    if (res.data.code === 1) {
      loadingInstance.close()
      return res.data
    } else if (res.data.code === 0) {
      loadingInstance.close()
      // location.replace('http://vue.projectsb.xnshehui.com/#/404')
      // console.log(location.pathname);
      window.location.href = '/#/404';
    } else {
      loadingInstance.close()
      Message.error(res.data.msg)
      return res.data
    }
  },
  err => {
    loadingInstance.close()
    Message.error('请求失败，请稍后再试')
    return Promise.reject(err)
  }
)

/* 统一封装get请求 */
export const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    service({
      method: 'get',
      url,
      params,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

/* 统一封装post请求  */
export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url,
      data,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}
